package com.fenxiangtech.mall.web.controller.v1;

import com.fenxiangtech.mall.entity.ThirdApp;
import com.fenxiangtech.mall.exception.UserInvalidException;
import com.fenxiangtech.mall.service.AppTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller("appTokenControllerV1")
@RequestMapping("/v1/token")
public class AppTokenController {

    @Autowired
    private AppTokenService appTokenService;

    /**
     * 第三方应用获取令牌
     */
    @PostMapping("/app")
    @ResponseBody
    public Map<String, String> getAppToken(@RequestBody @Valid ThirdApp thirdApp,
                                           BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            throw new UserInvalidException(errors.get(0).getDefaultMessage());
        }
        return appTokenService.getAppToken(thirdApp);
    }

}
